

import javax.activation.DataHandler;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.FileInputStream;

import java.util.ArrayList;

import java.util.List;
import java.util.Properties;

/**
 * Create by wzy on 18/6/22
 */
public class EmailSender  {

    private String hostName;
    private String charset;
    private Authenticator authenticator;
    private int port;


    EmailSender(String hostName, String charset, Authenticator authenticator, int port){
        this.hostName = hostName;
        this.charset = charset;
        this.authenticator = authenticator;
        this.port = port;
    }

    private static final int MAX_SEND_SIZE = 500;

    public boolean sendSimpleEmail(String fromAddress,String fromName, String sub, String content, List<String> toAddressList,
    List<AttachFileBo> attachFileList, List<EmbedImageBo> embedImageList){
        if (toAddressList == null || toAddressList.size()<=0) {
            throw new RuntimeException("toEmailAddressList is empty!");
        }
        if (toAddressList.size() > MAX_SEND_SIZE) {
            throw new RuntimeException("toEmailAddressList is more than [" + MAX_SEND_SIZE + "]!");
        }

        try {
            Session session = getSession();
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAddress, fromName, charset));
            message.setRecipients(Message.RecipientType.TO, getAddressArr(toAddressList));
            message.setSubject(sub, charset);
            //message.setContent(content, "text/html;charset="+charset);

            // 消息体
            MimeMultipart mainPart = new MimeMultipart();

            BodyPart body = new MimeBodyPart();
            body.setContent(content, "text/html;charset=UTF-8");
            mainPart.addBodyPart(body);

            // 附件
            if(attachFileList != null && attachFileList.size() > 0){
                for(AttachFileBo fileBo:attachFileList){
                    BodyPart attachFilePart = new MimeBodyPart();
                    attachFilePart.setDataHandler(new DataHandler(new ByteArrayDataSource(fileBo.getIn(), "application/octet-stream")));
                    attachFilePart.setFileName(fileBo.getFileName());
                    mainPart.addBodyPart(attachFilePart);
                }
            }

            // 内嵌图片
            if(embedImageList != null && embedImageList.size() > 0){
                for(EmbedImageBo embedImageBo : embedImageList){
                    BodyPart embedImagePart = new MimeBodyPart();
                    embedImagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(embedImageBo.getIn(), "application/octet-stream")));
                    ((MimeBodyPart) embedImagePart).setContentID(embedImageBo.getCid());
                    mainPart.addBodyPart(embedImagePart);
                }
            }

            message.setContent(mainPart);
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    private Session getSession(){
        // 获取系统属性
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", hostName);
        properties.setProperty("mail.smtp.port", String.valueOf(port));
        properties.setProperty("mail.debug", "false");
        properties.setProperty("mail.smtp.starttls.enable", "false");
        properties.setProperty("mail.smtp.starttls.required", "false");
        properties.setProperty("mail.smtp.sendpartial", "false");
        properties.setProperty("mail.smtps.sendpartial", "false");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.connectiontimeout", "60000");
        properties.setProperty("mail.smtp.timeout", "60000");

        return  Session.getDefaultInstance(properties, authenticator);
    }

    private InternetAddress[] getAddressArr(List<String> toAddressList) throws Exception{
        InternetAddress[] addressArr = new InternetAddress[toAddressList.size()];
        for(int i=0; i<toAddressList.size(); i++){
            addressArr[i] = new InternetAddress(toAddressList.get(i));
        }
        return addressArr;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setAuthenticator(Authenticator authenticator) {
        this.authenticator = authenticator;
    }

    public void setPort(int port) {
        this.port = port;
    }



    public static void main(String[] args) throws Exception{
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("582127421@qq.com", "rjcytsgrcxgobbii");
            }
        };

        EmailSender sender = new EmailSender("smtp.qq.com", "UTF-8", authenticator, 587);

        String content = "<span style=\"color:red\">很高兴认识你1222</span><img src='cid:123123123'>";
        List<String> toAddressList = new ArrayList<String>();
        toAddressList.add("2244701134@qq.com");
        toAddressList.add("shwangziying@jd.com");

        // 附件
        List<AttachFileBo> attachFileList= new ArrayList<AttachFileBo>();
        AttachFileBo attachFileBo = new AttachFileBo();
        attachFileBo.setIn(new FileInputStream(new File("/Users/jd/test.log")));
        attachFileBo.setFileName("test.log");
        attachFileList.add(attachFileBo);

        attachFileBo = new AttachFileBo();
        attachFileBo.setIn(new FileInputStream(new File("/Users/jd/Downloads/image002.png")));
        attachFileBo.setFileName("image002.png");
        attachFileList.add(attachFileBo);


        attachFileBo = new AttachFileBo();
        attachFileBo.setIn(new FileInputStream(new File("/Users/jd/Downloads/rarosx-5.6.b3.tar.gz")));
        attachFileBo.setFileName("rarosx-5.6.b3.tar.gz");
        attachFileList.add(attachFileBo);


        //内嵌图片
        List<EmbedImageBo> embedImageBoList = new ArrayList<EmbedImageBo>();
        EmbedImageBo embedImageBo = new EmbedImageBo();
        embedImageBo.setIn(new FileInputStream(new File("/Users/jd/Documents/5b29d9b0N1f334e90.jpg")));
        embedImageBo.setCid("123123123");
        embedImageBoList.add(embedImageBo);

        Boolean result = sender.sendSimpleEmail("582127421@qq.com", "王自英", "你好", content, toAddressList, attachFileList, embedImageBoList);
        System.out.println(result);
    }
}